const util = require('../../utils/util.js')

Page({
  data: {
    orderList: [],
    filteredOrderList: [],
    activeTab: '待支付',
    loading: true,
    currentTime: null
  },
  onLoad() {
    this.loadOrderList();
    const now = new Date()
    const cur = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDay()} ${now.getHours()}:${now.getMinutes()}`
    this.setData({
      currentTime: cur
    })
  },

  // 加载订单列表
  loadOrderList() {
    wx.showLoading({
      title: '加载中...',
    });

    this.setData({
      loading: true
    });

    util.callContainerApi("/order/list", "GET", null)
      .then(res => {
        if (res.data && res.data.data) {
          // 处理订单数据
          const processedOrders = this.processOrderData(res.data.data);

          this.setData({
            "orderList": processedOrders,
            loading: false
          });

          this.filterOrders();
        } else {
          this.setData({
            "orderList": [],
            loading: false
          });
        }
        wx.hideLoading();
      }).catch(err => {
        console.error('获取订单列表失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '获取订单失败',
          icon: 'error'
        });
        this.setData({
          loading: false
        });
      });
  },

  // 处理订单数据
  processOrderData(orders) {
    const merchantList = wx.getStorageSync('merchantList')
    return orders.map(order => {
      for (const item of merchantList) {
        if (item.merchantId === order.merchantId) {
          order.merchantName = item.merchantName
        }
      }
      // 格式化创建时间
      if (order.createAt) {
        order.createTime = util.formatTime(order.createAt);
        order.closeTime = util.offsetDay(order.createAt)
      }
      // 获取商品预览信息
      if (order.childs && order.childs.length > 0) {
        const firstGoods = order.childs[0];
        order.goodsPreview = {
          name: firstGoods.merchandiseName || '商品名称',
          spec: firstGoods.specDesc || '',
          price: firstGoods.singlePrice || 0,
          count: firstGoods.num || 1,
          image: firstGoods.file_id || firstGoods.fild_id || '/images/default-goods.png'
        };
        order.goodsCount = order.childs.length;
      }
      return order;
    });
  },

  onShow() {
    this.filterOrders()
  },
  findOrderById(id) {
    const {
      filteredOrderList
    } = this.data
    for (const item of filteredOrderList) {
      if (item.orderId === id) {
        return item
      }
    }
  },
  filterOrders() {
    const {
      orderList,
      activeTab
    } = this.data;
    let filteredOrderList = [];
    switch (activeTab) {
      case '待支付':
        filteredOrderList = orderList.filter(order => order.status === 'Create')
        break
      case '待收货':
        filteredOrderList = orderList.filter(order => order.status === 'Payed' || order.status === 'Accept' || order.status === 'Send')
        break
      case '已完成':
        filteredOrderList = orderList.filter(order => order.status === 'Finish')
        break
    }
    this.setData({
      "filteredOrderList": filteredOrderList
    });
  },
  onTabChange(e) {
    const activeTab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab
    });
    this.filterOrders();
  },
  // 显示订单详情
  showOrderDetail(e) {
    const {
      currentTime
    } = this.data
    const orderId = e.currentTarget.dataset.id;
    const order = this.findOrderById(orderId)

    if (order.status === "Create" && order.closeTime < currentTime) {
      util.showErrorToast("当前订单已经过期")
      return
    } else {
      // 这里可以添加具体的详情展示逻辑，比如跳转到详情页
      wx.navigateTo({
        url: `/pages/orderDetail/orderDetail?id=${orderId}`,
      })
    }
  },
  // 删除待支付订单
  deleteOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    util.callContainerApi(`/order/cancel?orderId=${orderId}`, "DELETE", null)
      .then(res => {
        let {
          orderList
        } = this.data;
        orderList = orderList.filter(order => order.id !== orderId);
        this.setData({
          orderList
        })
        this.filterOrders()
        wx.showToast({
          title: '订单已删除',
          icon: 'success'
        })
      })

  },
  // 支付待支付订单
  async payOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/orderDetail/orderDetail?id=${orderId}&pay=true`,
    })

  },
  // 确认收货
  confirmReceipt(e) {
    const orderId = e.currentTarget.dataset.id

    util.callContainerApi(`/order/finish?orderId=${orderId}`, "POST", null)
      .then(res => {
        wx.showToast({
          title: '确认收货成功',
          icon: 'success'
        });
        this.loadOrderList()
      })

    let {
      orderList
    } = this.data;
    const index = orderList.findIndex(order => order.id === orderId);
    if (index !== -1) {
      orderList[index].status = 'Finish';
      wx.setStorageSync('orderList', orderList);
      this.setData({
        orderList
      });
      this.filterOrders();

    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadOrderList();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});